<template>
	<view class="container">
		<view class="titleTop">
			<view class="text"> 1RM测试-{{ mode }}模式 </view>
			<image class="line" src="../static/line.png" mode="widthFix"></image>
		</view>
		<view class="stepBox selectAction" v-if="pageStep == 1">
			<view class="tip"> 请选择动作 </view>
			<view class="actionSelectRow">
				<view class="actionItem" v-for="(item, index) in actionsArr" :key="index"
					@click="handleSelectAction(item, index)">
					<image :src="item.icon" mode=""></image>
					<view class="right">
						<view class="title">{{ item.title }}</view>
						<view class="content">{{ item.content }}</view>
						<view class="content">{{ item.content2 }}</view>
					</view>
				</view>
			</view>
		</view>

		<view class="stepBox inputBoxRow" v-else-if="pageStep == 2">
			<view class="tip"> 请先输入主观感受的一次动作极限重量 </view>
			<view class="inputBox">
				<input type="number" :value="limitWeight" @blur="inputBlur" maxlength="3" auto-focus />
				<text style="font-size: 24px; color: #6e58aa"> KG</text>
			</view>
			<view class="btnBox" @click="nextStep"> 确定 </view>
		</view>

		<view class="stepBox testRow" v-else>
			<view v-if="isCompleted">
				<view class="textBox">
					<view class="text1"> 恭喜完成测试！ </view>
					<view class="text2">
						您的{{ accurateE1rm ? "精准" : "参考" }}1RM为：
					</view>
				</view>
				<view class="E1rm">
					{{ accurateE1rm ? accurateE1rm : firstE1rm }}
					<text style="font-size: 20px"> KG </text>
				</view>
			</view>
			<view v-else>
				<view class="tip" style="margin-top: 68px">
					<template v-if="customWeightMode && maxTestedWeight > 0">
						请用{{ maxTestedWeight }}kg以上的重量最快速度做一次动作
					</template>
					<template v-else>
						请用此重量最快速度做一次动作
					</template>
				</view>
				<view class="swiperRow">
					<swiper :current="current" @change="swiperChange" style="height: 100px; width:100%" duration="800">
						<swiper-item v-for="(item, index) in weightItems" :key="index">
							<view class="swiperItem">
								<view class="weight" @click="handleWeightClick(index)">
									<view
										v-if="customWeightMode && (index == editingWeightIndex) && (weightItems[index].status == STATUS.READY)">
										<input class="weight-input" type="number" v-model="weightItems[index].weight"
											placeholder="请输入" focus @blur="handleWeightInputBlur(index)" />
									</view>
									<view v-else>
										{{ item.weight }}
									</view>
									<view class="unit">
										<view> KG </view>
										<view v-if="smwStatus[index] == 0" class="round red"></view>
										<view v-else-if="smwStatus[index] == 1" class="round yellow"></view>
										<view v-else-if="smwStatus[index] == 2" class="round green"></view>
									</view>
								</view>
							</view>
						</swiper-item>
					</swiper>
				</view>
			</view>

			<view class="echartBox">
				<l-echart ref="chartRef" @finished="initChart"></l-echart>
			</view>

			<view v-if="isCompleted">
				<view class="content" v-if="mode == '复杂'">
					<image src="../../static/imgs/infoImg.png" mode=""></image>
					<view style="width: 91%">
						首次测量只能获得参考1RM值,测量结束后务必点击“记录”,后续测量可获得精准1RM值。建议每次测量与上次测量有一定时间间隔.
					</view>
				</view>
				<view class="content" v-else>
					注意：<br />
					<view style="text-indent: 2em">
						测量结束后<text style="font-weight: 600">务必点击记录</text>
					</view>
				</view>
				<view class="btnBox" @click="handleRecord"> 记录 </view>
			</view>
			<view v-else>
				<view v-if="customWeightMode && smwStatus[currentWeightIndex] == 1" class="btnBox-row">
					<view class="btnBox2 fail" @click="handleLiftFail">
						举起失败
					</view>
					<view class="btnBox2 success" @click="handleWeightAction(currentWeightIndex)">
						举起成功
					</view>
				</view>
				<view v-else class="btnBox" @click="handleWeightAction(currentWeightIndex)">
					{{ getButtonText(smwStatus[currentWeightIndex]) }}
				</view>
			</view>
		</view>
		<Countdown ref="countdownRef" />
	</view>
</template>

<script>
	import * as echarts from "../static/echarts.min.js";
	import Countdown from "@/components/countdown/countdown.vue";
	import tool from "@/utils/tool.js";
	import VueEvent from "../../VueEvent.js";
	import * as Utils from '@/cal/vbt.js'
	import {
		recordSpeedEasy,
		recordSpeed,
		getVZeroRecord
	} from "../../apis/e1rm.js";
	import action1 from '@/static/imgs/action1.png'

	export default {
		props: ['mode'],
		data() {
			// 根据模式初始化重量项

			const weightItems = [{
					percent: 0.35,
					weight: 0,
					status: 0
				},
				{
					percent: 0.75,
					weight: 0,
					status: 0
				}
			];

			return {
				STATUS: {
					READY: 0,
					IN_PROGRESS: 1,
					COMPLETED: 2
				},
				// 新增变量
				editingWeightIndex: -1, // 正在编辑的重量项索引
				customWeightMode: false, // 是否处于自定义重量模式
				customWeight: 0, // 用户自定义的重量值
				maxTestedWeight: 0, // 已测试的最大重量
				liftFailed: false, // 是否举起失败
				regressionData: null, // 回归直线数据
				lastSuccessWeight: 0, // 最后成功举起的重量
				lastSuccessSpeed: 0, // 最后成功举起的速度
				maxSuccessWeight: 0, // 最大成功举起的重量
				maxSuccessSpeed: 0, // 最大成功举起重量对应的速度,
				customWeightCompleted: false, // 新增：标记自定义重量测试是否已完成
				deviceData: {}, // 当前连接的蓝牙设备信息
				current: 0, // 当前选中的重量索引
				pageStep: 1, // 页面步骤：1-选动作, 2-输重量, 3-测试
				limitWeight: 0, // 用户输入的极限重量
				weightItems, // 重量项数组
				// 传感器数据分开存储
				accelerometerData: [], // 加速度计数据
				deviceMotionData: [], // 设备运动数据
				bluetoothData: [], // 蓝牙传感器数据
				penddingStatus: -1, // 当前正在进行测试的重量索引
				chartInstance: null, // ECharts实例
				firstE1rm: 0, // 首次测量的1RM值
				accurateE1rm: 0, // 精准1RM值
				action: "深蹲", // 当前选择的动作
				actionIndex: 0, //选择的动作索引
				isFirstTest: true, // 是否首次测试
				firstE1rmDataSource: [], // 首次测试数据源
				testSequence: [0, 1], // 默认测试顺序：35%和75%
				currentTestIndex: 0, // 当前测试序列索引
				v0: null,
				allActionData: [], //所有动作数据
				actionsArr: [{
						title: '深蹲',
						content: '锻炼下肢力量的基础动作',
						content2: '股四头肌、臀肌',
						icon: action1
					},
					{
						title: '卧推',
						content: '增强上肢推力的经典动作',
						content2: '胸大肌、三头肌',
						icon: action1
					},
					{
						title: '硬拉',
						content: '全身性力量训练动作',
						content2: '背阔肌、臀腿',
						icon: action1
					},
					{
						title: '高翻',
						content: '爆发力训练动作',
						content2: '全身性动作',
						icon: action1
					},
					{
						title: '坐姿推肩',
						content: '肩部力量发展动作',
						content2: '三角肌、斜方肌',
						icon: action1
					},
					{
						title: '俯身划船',
						content: '强化背部的基础动作',
						content2: '背阔肌、斜方肌',
						icon: action1
					},
					{
						title: '站姿推肩',
						content: '肩部力量发展动作',
						content2: '三角肌、斜方肌',
						icon: action1
					},
					{
						title: '高位下拉',
						content: '强化背部的基础动作',
						content2: '背阔肌、斜方肌',
						icon: action1
					}
				], //动作列表
				option: {
					title: {
						show: true,
						text: "单位:m/s",
						textAlign: "center",
						top: "3%",
						left: "50%",
						textStyle: {
							fontSize: "14"
						},
					},
					tooltip: {
						triggerOn: "none",
						formatter: params =>
							`X: ${params.data[0].toFixed(2)}<br>Y: ${params.data[1].toFixed(2)}`
					},
					xAxis: {
						name: "V",
						type: "value",
						splitLine: {
							show: false
						},
						axisLine: {
							lineStyle: {
								color: "#7C7C7E"
							}
						},
					},
					yAxis: {
						name: "F",
						type: "value",
						axisLine: {
							show: false,
							lineStyle: {
								color: "#7C7C7E"
							}
						},
						axisTick: {
							show: false
						},
						splitLine: {
							lineStyle: {
								color: ["#7C7C7E"]
							}
						},
					},
					series: [{
						data: [
							[],
							[],
							[],
							[],
							[]
						],
						smooth: true,
						symbolSize: 8,
						type: "scatter",
						itemStyle: {
							normal: {
								color: "#000"
							}
						},
						label: {
							show: true,
							position: "top",
							formatter: param => Number(param.data[0]).toFixed(2)
						}
					}]
				}
			};
		},
		computed: { // 重量项状态数组
			smwStatus() {
				return this.weightItems.map(item => item.status);
			}, // 当前选中的重量索引
			currentWeightIndex() {
				return this.current;
			},
			// 当前重量项
			currentItem() {
				return this.weightItems[this.currentWeightIndex];
			},
			// 是否所有测试都已完成
			isCompleted() {
				// 如果自定义重量模式已完成，显示完成页面
				if (this.customWeightMode && this.customWeightCompleted) {
					return true;
				}
				// 如果处于自主加重量模式但未完成，则不显示完成页面
				if (this.customWeightMode && !this.customWeightCompleted) {
					return false;
				}
				return this.weightItems.every(item => item.status == this.STATUS.COMPLETED);
			}
		},
		watch: {
			// 监听重量输入变化更新重量项
			limitWeight(newVal) {
				this.updateWeights();
			}
		},
		methods: {
			/** 初始化页面 */
			initializePage() {
				uni.showModal({
					title: "温馨提示",
					content: "下面将进行您个性化FV曲线建立，请注意：\r\n1.确保充分热身\r\n2.请确保传感器（手机或其他）固定于杠铃杆\r\n3.确保已获得良好的休息恢复\r\n4.请确保您是一位有经验的训练者，且有同样丰富经验的训练伙伴进行安全保护",
					showCancel: false,
				});
				// 初始化v0值
				this.initializeV0();
			},

			/** 初始化v0值 */
			initializeV0() {
				// 根据动作类型设置默认v0值
				const v0Map = {
					'深蹲': 0.3,
					'卧推': 0.17,
					'站姿推肩': 0.19,
					'坐姿推肩': 0.19,
					'划船': 0.40,
					'硬拉': 0.15,
					'直腿硬拉': 0.15,
					'罗马尼亚硬拉': 0.15,
					'高位下拉': 0.47
				};
				if (this.mode == "简单") {
					this.v0 = v0Map[this.action]
				} else {
					if (this.allActionData.length > 0) {
						let obj = this.allActionData.find(v => v.action == this.action) || {}
						this.v0 = obj?.v0 || null
						// this.v0 = null
					} else {
						this.v0 = null
					}
				}
				console.log('v0', this.v0);
			},

			/** 获取圆点状态样式 */
			getRoundStyle(status) {
				switch (status) {
					case this.STATUS.READY:
						return {
							round: true, red: true,
						};
					case this.STATUS.IN_PROGRESS:
						return {
							round: true, yellow: true,
						};
					case this.STATUS.COMPLETED:
						return {
							round: true, green: true,
						};
					default:
						return {};
				}
			},

			/** 获取按钮文本 */
			getButtonText(status) {
				// 如果处于自定义重量模式且正在进行测试
				if (this.customWeightMode && status == this.STATUS.IN_PROGRESS) {
					return '举起成功';
				}

				// 如果处于自定义重量模式且举起失败
				if (this.customWeightMode && this.liftFailed) {
					return '重做';
				}

				// 默认状态
				switch (status) {
					case this.STATUS.READY:
						return '开始';
					case this.STATUS.IN_PROGRESS:
						return '结束';
					case this.STATUS.COMPLETED:
						return '重做';
					default:
						return '';
				}
			},

			/** 处理举起失败 */
			handleLiftFail() {
				if (!this.customWeightMode) return;

				// 获取当前测试序列中的实际索引
				let actualIndex = this.currentWeightIndex;

				this.stopSensors();
				this.liftFailed = true;
				this.penddingStatus = -1;

				// 显示失败后的选项
				uni.showActionSheet({
					itemList: ["重做", "结束测试"],
					success: (res) => {
						if (res.tapIndex == 0) {
							// 选择重做
							this.weightItems[actualIndex].status = this.STATUS.READY;
							this.liftFailed = false;
						} else {
							// 选择结束测试
							// 如果有成功记录，直接计算1RM，v0会在calculateE1RM中处理
							if (this.maxSuccessWeight > 0 || this.lastSuccessWeight > 0) {
								// 不改变 customWeightMode，而是设置完成标志
								this.customWeightCompleted = true;
								this.calculateE1RM();
							} else {
								uni.showToast({
									title: "没有成功记录，无法计算1RM",
									icon: "none"
								});
							}
						}
					}
				});
			},

			/** 更新重量项数值 */
			updateWeights() {
				this.weightItems = this.weightItems.map(item => ({
					...item,
					weight: Math.round(this.limitWeight * item.percent / 5) * 5
				}));
			},

			/** 轮播图切换回调 */
			swiperChange(e) {
				const newIndex = e.detail.current;

				// 如果是自定义重量模式，允许自由切换
				if (this.customWeightMode) {
					this.current = newIndex;
					return;
				}

				// 非自定义重量模式下的逻辑
				const isInSequence = this.testSequence.includes(newIndex);
				const isCurrentOrCompleted = newIndex == this.testSequence[this.currentTestIndex] ||
					this.weightItems[newIndex].status == this.STATUS.COMPLETED;

				if (isInSequence && isCurrentOrCompleted) {
					this.current = newIndex;
				} else {
					// 如果不是当前应该测试的索引，回到当前测试索引
					this.$nextTick(() => {
						this.current = this.testSequence[this.currentTestIndex];
					});

					uni.showToast({
						title: `请按顺序完成测试`,
						icon: "none"
					});
				}
			},

			/** 进入下一步 */
			nextStep() {
				if (this.pageStep == 2 && !this.limitWeight) {
					uni.showToast({
						title: "请先输入重量",
						icon: "none"
					});
					return;
				}
				this.pageStep++;
			},
			/** 显示自定义重量输入框 */
			showCustomWeightInput() {
				// 设置最大测试重量为当前已测试的最大重量
				this.maxTestedWeight = Math.max(...this.weightItems.map(item => parseFloat(item.weight) || 0));

				// 添加新的空重量项
				const newIndex = this.weightItems.length;
				this.weightItems.push({
					weight: "", // 初始为空
					status: this.STATUS.READY,
					percent: 1 // 默认百分比，实际值会在输入后更新
				});

				// 更新当前索引并进入编辑模式
				this.current = newIndex;
				console.log('newIndex', newIndex);
				this.editingWeightIndex = newIndex;


				console.log('设置editingWeightIndex为', newIndex);
				console.log('weightItems长度:', this.weightItems.length);
				console.log('新添加项的status:', this.weightItems[newIndex].status);
				console.log('customWeightMode:', this.customWeightMode);
			},

			/** 添加自定义重量项 */
			addCustomWeightItem(weight) {
				// 添加新的重量项
				const newIndex = this.weightItems.length;
				this.weightItems.push({
					weight: weight.toFixed(2),
					status: this.STATUS.READY,
					percent: weight / this.limitWeight
				});

				// 更新当前索引
				this.current = newIndex;
				this.customWeight = weight;

				// 更新图表y轴的最大值，确保能显示新添加的重量
				this.updateChartYAxisMax(weight);
			},

			/** 处理重量点击 */
			handleWeightClick(index) {
				// 只有在自主重量模式下且状态为READY时才允许编辑
				if (this.customWeightMode && this.weightItems[index].status == this.STATUS.READY) {
					this.editingWeightIndex = index;
				}
			},

			/** 处理重量输入框失焦 */
			handleWeightInputBlur(index) {
				// 验证输入的重量
				const weight = parseFloat(this.weightItems[index].weight);

				// 如果是最后一个项目（新添加的自定义重量）
				if (index == this.weightItems.length - 1) {
					// 验证重量必须大于已测试的最大重量
					if (isNaN(weight) || weight <= this.maxTestedWeight) {
						uni.showToast({
							title: `重量必须大于${this.maxTestedWeight}KG`,
							icon: "none"
						});
						// 重置为空，保持编辑状态
						this.weightItems[index].weight = "";
						return;
					}

					// 格式化重量为两位小数
					this.weightItems[index].weight = weight.toFixed(2);
					// 更新图表y轴的最大值
					this.updateChartYAxisMax(weight);
				}

				// 退出编辑模式
				this.editingWeightIndex = -1;
			},

			/** 更新图表y轴的最大值 */
			updateChartYAxisMax(weight) {
				// 获取当前y轴的最大值
				const currentMax = this.option.yAxis.max || this.limitWeight;

				// 如果新重量大于当前最大值，更新y轴最大值
				if (weight > currentMax) {
					// 设置新的最大值，并增加一些余量
					this.option.yAxis.max = Math.ceil(weight * 1.1);

					// 更新图表
					this.$refs.chartRef.setOption(this.option);
				}
			},
			/** 选择动作处理 */
			handleSelectAction(item, index) {
				// console.log(item);
				this.action = item.title;
				this.actionIndex = index
				this.initializeV0();
				setTimeout(() => this.nextStep(), 100);
			},

			/** 初始化图表 */
			async initChart() {
				const chart = await this.$refs.chartRef.init(echarts);
				chart.setOption(this.option);
			},

			/** 获取测试记录API */
			getE1rmZeroRecordApi() {
				getVZeroRecord({
					flag: this.mode == '复杂' ? 2 : 1
				}).then(res => {
					if (res.data) {
						this.allActionData = res.data
					}
				});
			},

			/** 记录结果处理 */
			handleRecord() {
				const params = this.mode == '复杂' ?
					this.buildComplexParams() :
					this.buildSimpleParams();

				const apiFunc = this.mode == '复杂' ? recordSpeed : recordSpeedEasy;
				console.log('记录参数', params);
				apiFunc(params).then(res => {
					console.log('记录结果', res);
					if (res.status == "success") {
						uni.showToast({
							title: "记录成功！",
							icon: "none"
						});
					}
				});
			},

			/** 构建复杂模式参数 */
			buildComplexParams() {
				return {
					action: this.action,
					measurementModel: "complex",
					referential1RM: null,
					accurate1RM: this.accurateE1rm,
					isFirstTest: false,
					complexTestList: this.weightItems.map((item, index) => ({
						weight: Number(this.option.series[0].data[index][1]),
						speed: Number(this.option.series[0].data[index][0]),
					})),
					c1rm: this.accurateE1rm,
					s1rm: null,
					v0: this.v0
				};
			},

			/** 构建简单模式参数 */
			buildSimpleParams() {
				return {
					action: this.action,
					measurementModel: "simple",
					simple1RM: String(this.firstE1rm),
					rmList: this.weightItems.map((item, index) => ({
						weight: Number(this.option.series[0].data[index][1]),
						speed: Number(this.option.series[0].data[index][0]),
					})),
					c1rm: null,
					s1rm: this.accurateE1rm,
					v0: this.v0
				};
			},

			/** 输入框失焦处理 */
			inputBlur(e) {
				this.limitWeight = Number(e.detail.value);
				this.weightItems.forEach(item => item.status = this.STATUS.READY);
				this.penddingStatus = -1;
			},

			/** 重置重量测试 */
			reset(index) {
				if (this.penddingStatus != -1) {
					uni.showToast({
						title: "当前有正在做的重量，请先结束",
						icon: "none"
					});
					return;
				}
				this.weightItems[index].status = this.STATUS.READY;
				this.option.series[0].data[index] = [];
				this.$refs.chartRef.setOption(this.option);
				this.penddingStatus = -1;
			},

			/** 开始传感器数据收集 */
			startSensors() {
				this.deviceData = uni.getStorageSync("deviceData");
				this.clearSensorsData();

				if (this.deviceData && this.deviceData.localName != "手机") {
					tool.onBLEData(this.deviceData.deviceId, this.processSensorData);
				} else {
					uni.startAccelerometer({
						interval: "game",
						success: () => uni.onAccelerometerChange(this.processAccelerometerData),
						fail: console.error
					});

					uni.startDeviceMotionListening({
						interval: "game",
						success: () => uni.onDeviceMotionChange(this.processDeviceMotionData),
						fail: console.error
					});
				}
				this.$refs.countdownRef.startCountdown();
			},

			/** 处理蓝牙传感器数据 */
			processSensorData(res) {
				if (res.length > 0) {
					res.forEach(item => {
						this.bluetoothData.push({
							x: item.measured_acceleration_x,
							y: item.measured_acceleration_y,
							z: item.measured_acceleration_z,
							wx: item.angular_velocity_x,
							wy: item.angular_velocity_y,
							wz: item.angular_velocity_z
						});
					});
				}
			},

			/** 处理加速度计数据 */
			processAccelerometerData(res) {
				this.accelerometerData.push({
					x: res.x,
					y: res.y,
					z: res.z
				});
			},

			/** 处理设备运动数据 */
			processDeviceMotionData(res) {
				this.deviceMotionData.push({
					alpha: res.alpha,
					beta: res.beta,
					gamma: res.gamma
				});
			},

			/** 清空传感器数据 */
			clearSensorsData() {
				this.accelerometerData = [];
				this.deviceMotionData = [];
				this.bluetoothData = [];
			},

			/** 停止所有传感器 */
			stopSensors() {
				if (this.deviceData && this.deviceData.localName != "手机") {
					tool.closeOnBLE();
				} else {
					uni.stopAccelerometer();
					uni.stopDeviceMotionListening();
					uni.offAccelerometerChange();
					uni.offDeviceMotionChange();
				}
			},

			/** 重量项动作处理 */
			handleWeightAction(index) {
				// 获取当前测试序列中的实际索引
				let actualIndex;

				// 如果是自定义重量模式，直接使用当前索引
				if (this.customWeightMode) {
					actualIndex = index;
				} else {
					// 否则使用测试序列中的索引
					actualIndex = this.testSequence[this.currentTestIndex];
				}

				if (index != actualIndex) {
					uni.showToast({
						title: `请先完成当前重量(${this.weightItems[actualIndex].weight}KG)的测试`,
						icon: "none"
					});
					return;
				}

				const item = this.weightItems[actualIndex];

				if (!this.validateAction(actualIndex)) return;

				switch (item.status) {
					case this.STATUS.READY:
						this.startWeightTest(actualIndex);
						break;
					case this.STATUS.IN_PROGRESS:
						this.endWeightTest(actualIndex);
						break;
					case this.STATUS.COMPLETED:
						this.reset(actualIndex);
						break;
				}
			},

			/** 验证重量操作 */
			validateAction(index) {
				if (!this.limitWeight) {
					uni.showToast({
						title: "请先输入重量",
						icon: "none"
					});
					return false;
				}

				// 新增：自定义重量模式下，验证当前重量项是否有输入值
				if (this.customWeightMode && (!this.weightItems[index].weight || parseFloat(this.weightItems[index]
						.weight) <= 0)) {
					uni.showToast({
						title: "请先输入重量",
						icon: "none"
					});
					return false;
				}

				if (!this.action) {
					uni.showToast({
						title: "请先选择动作",
						icon: "none"
					});
					return false;
				}

				if (this.penddingStatus != -1 && this.penddingStatus != index) {
					uni.showToast({
						title: "请先结束当前其他正在做的重量",
						icon: "none"
					});
					return false;
				}

				if (this.weightItems[index].status == this.STATUS.COMPLETED) {
					uni.showToast({
						title: "当前重量已做完，如需重做，请点击重做按钮",
						icon: "none"
					});
					return false;
				}

				return true;
			},

			/** 开始重量测试 */
			startWeightTest(index) {
				if (this.mode == '复杂' && index == 4) {
					uni.showModal({
						title: "温馨提示",
						content: "最高重量测试有一定风险，请确保你的安全！",
						success: (res) => {
							if (res.confirm) this.doStartTest(index);
						},
						showCancel: false,
					});
					return;
				}
				this.doStartTest(index);
			},

			/** 执行开始测试 */
			doStartTest(index) {
				this.weightItems[index].status = this.STATUS.IN_PROGRESS;
				this.penddingStatus = index;
				this.startSensors();
			},

			/** 结束重量测试 */
			endWeightTest(index) {
				this.stopSensors();
				const item = this.weightItems[index];
				const weight = this.getSmw(item.percent).toFixed(2);

				this.calculateSpeed(index, weight).then(() => {
					this.penddingStatus = -1;
					this.moveToNextTest(index);
				}).catch(() => {
					this.weightItems[index].status = this.STATUS.READY;
					this.option.series[0].data[index] = [];
					this.$refs.chartRef.setOption(this.option);
					uni.showToast({
						title: "未检测到完整动作，请点击重做",
						icon: "none"
					});
				});
			},

			/** 计算速度并更新图表 */
			calculateSpeed(index, weight) {
				return new Promise((resolve, reject) => {
					let x = [],
						y = [],
						z = [],
						alpha = [],
						beta = [],
						gamma = [];

					// 根据设备类型选择使用哪种数据
					if (this.deviceData && this.deviceData.localName != "手机") {
						// 使用蓝牙数据
						x = this.bluetoothData.map(d => d.x);
						y = this.bluetoothData.map(d => d.y);
						z = this.bluetoothData.map(d => d.z);
						// 蓝牙设备可能没有方向数据，使用默认值
						alpha = new Array(x.length).fill(0);
						beta = new Array(x.length).fill(0);
						gamma = new Array(x.length).fill(0);
					} else {
						// 使用手机传感器数据
						x = this.accelerometerData.map(d => d.x);
						y = this.accelerometerData.map(d => d.y);
						z = this.accelerometerData.map(d => d.z);

						// 确保方向数据与加速度数据长度一致
						const motionLength = this.deviceMotionData.length;
						const accelLength = this.accelerometerData.length;

						// 如果有方向数据，使用它们；否则使用默认值
						if (motionLength > 0) {
							// 处理数据长度不一致的情况
							if (motionLength == accelLength) {
								alpha = this.deviceMotionData.map(d => d.alpha);
								beta = this.deviceMotionData.map(d => d.beta);
								gamma = this.deviceMotionData.map(d => d.gamma);
							} else {
								// 数据长度不一致时的处理策略
								alpha = new Array(accelLength).fill(0);
								beta = new Array(accelLength).fill(0);
								gamma = new Array(accelLength).fill(0);

								// 尽可能使用可用的方向数据
								const minLength = Math.min(motionLength, accelLength);
								for (let i = 0; i < minLength; i++) {
									alpha[i] = this.deviceMotionData[i].alpha || 0;
									beta[i] = this.deviceMotionData[i].beta || 0;
									gamma[i] = this.deviceMotionData[i].gamma || 0;
								}
							}
						} else {
							alpha = new Array(accelLength).fill(0);
							beta = new Array(accelLength).fill(0);
							gamma = new Array(accelLength).fill(0);
						}
					}

					// 调用simple_update函数
					const res = Utils.default.simple_update(x, y, z, alpha, beta, gamma, 0, this.actionIndex, 100,
						70, 0, 0, 0.02);
					console.log('simple update返回值------------', res);

					if (res && res.averagy_v_value && res.flag) {
						this.option.series[0].data[index] = [res.averagy_v_value, weight];
						this.$refs.chartRef.setOption(this.option);

						// 更新最后成功的速度和重量
						this.lastSuccessSpeed = res.averagy_v_value;
						this.lastSuccessWeight = parseFloat(weight);

						// 更新最大成功重量及其对应的速度
						if (parseFloat(weight) > this.maxSuccessWeight) {
							this.maxSuccessWeight = parseFloat(weight);
							this.maxSuccessSpeed = res.averagy_v_value;
							// 同步更新maxTestedWeight
							this.maxTestedWeight = this.maxSuccessWeight;
						}

						resolve();
					} else {
						reject();
					}
				});
			},

			/** 处理传感器加速度数据 */
			getAccelerationData() {
				// 简化的加速度数据处理
				let x = [],
					y = [],
					z = [],
					alpha = [],
					beta = [],
					gamma = [];

				// 合并蓝牙数据
				if (this.bluetoothData.length > 0) {
					x = this.bluetoothData.map(d => d.x);
					y = this.bluetoothData.map(d => d.y);
					z = this.bluetoothData.map(d => d.z);
				}

				// 合并加速度计数据
				if (this.accelerometerData.length > 0) {
					x = this.accelerometerData.map(d => d.x);
					y = this.accelerometerData.map(d => d.y);
					z = this.accelerometerData.map(d => d.z);
				}

				// 合并设备运动数据
				if (this.deviceMotionData.length > 0) {
					alpha = this.deviceMotionData.map(d => d.alpha || 0);
					beta = this.deviceMotionData.map(d => d.beta || 0);
					gamma = this.deviceMotionData.map(d => d.gamma || 0);
				}

				const res = VueEvent.xyz_to_y(x, y, z, alpha, beta, gamma);

				const local_g = res.length >= 130 ?
					res.slice(30, 130).reduce((sum, val) => sum + val, 0) / 100 :
					res[res.length - 1] || 0;

				return res.slice(30).map(i => parseFloat((parseFloat(i) - parseFloat(local_g)).toFixed(7)));
			},

			/** 移动到下一项测试 */
			moveToNextTest(index) {
				this.weightItems[index].status = this.STATUS.COMPLETED;
				this.clearSensorsData();

				// 更新当前测试序列索引
				this.currentTestIndex++;

				// 检查是否需要进行55%测试（仅在完成75%测试后检查）
				if (this.currentTestIndex == 2 && this.testSequence.length == 2 && !this.customWeightMode) {
					// 获取35%和75%的速度
					const speed35 = this.option.series[0].data[0][0];
					const speed75 = this.option.series[0].data[1][0];

					// 如果速度差小于0.2，添加55%测试
					if (Math.abs(speed35 - speed75) < 0.2) {
						this.weightItems.push({
							weight: this.getSmw(0.55).toFixed(2),
							status: this.STATUS.READY,
							percent: 0.55,
						});
						this.testSequence.push(2); // 添加55%测试
					}
				}

				// 检查是否还有测试需要进行
				if (this.currentTestIndex < this.testSequence.length) {
					// 移动到测试序列中的下一个测试
					this.current = this.testSequence[this.currentTestIndex];
				} else if (this.v0 == null) {
					// 如果v0为空，进入自定义重量测试阶段
					// 计算回归直线数据，但不绘制回归线
					this.calculateRegressionDataOnly();
					// 显示自定义重量输入框并进入自定义重量模式
					this.customWeightMode = true;
					console.log('将customWeightMode变为true', this.customWeightMode);
					this.showCustomWeightInput();
				} else {
					// 所有测试完成，计算1RM
					this.calculateE1RM();
				}
			},

			/** 只计算回归数据，不绘制回归线 */
			calculateRegressionDataOnly() {
				// 收集所有已完成测试的速度和重量数据
				const speedArray = [];
				const weightArray = [];

				this.testSequence.forEach(index => {
					if (this.weightItems[index].status == this.STATUS.COMPLETED &&
						this.option.series[0].data[index] &&
						this.option.series[0].data[index].length == 2) {
						speedArray.push(this.option.series[0].data[index][0]);
						weightArray.push(this.option.series[0].data[index][1]);
					}
				});

				if (speedArray.length < 2) {
					uni.showToast({
						title: "测试数据不足，无法计算回归线",
						icon: "none"
					});
					return null;
				}

				try {
					// 使用最小二乘法计算斜率和截距
					console.log('speedArray-----calculateRegressionDataOnly', speedArray);
					console.log('weightArray------calculateRegressionDataOnly', weightArray);
					const regression = tool.leastSquaresRegression(speedArray, weightArray);
					this.regressionData = regression;
					return regression;
				} catch (error) {
					console.error("计算回归线出错:", error);
					uni.showToast({
						title: "计算回归线出错，请重试",
						icon: "none"
					});
					return null;
				}
			},

			/** 计算回归直线并绘制 */
			calculateRegressionLine() {
				// 收集所有已完成测试的速度和重量数据
				const speedArray = [];
				const weightArray = [];

				this.testSequence.forEach(index => {
					if (this.weightItems[index].status == this.STATUS.COMPLETED &&
						this.option.series[0].data[index] &&
						this.option.series[0].data[index].length == 2) {
						speedArray.push(this.option.series[0].data[index][0]);
						weightArray.push(this.option.series[0].data[index][1]);
					}
				});

				if (speedArray.length < 2) {
					uni.showToast({
						title: "测试数据不足，无法计算回归线",
						icon: "none"
					});
					return null;
				}

				try {
					// 使用最小二乘法计算斜率和截距
					console.log('speedArray-----calculateRegressionLine', speedArray);
					console.log('weightArray------calculateRegressionLine', weightArray);
					const regression = tool.leastSquaresRegression(speedArray, weightArray);
					this.regressionData = regression;

					// 添加线性回归线
					this.addLinearSeries(regression);

					return regression;
				} catch (error) {
					console.error("计算回归线出错:", error);
					uni.showToast({
						title: "计算回归线出错，请重试",
						icon: "none"
					});
					return null;
				}
			},
			/** 计算1RM */
			calculateE1RM() {
				// 如果已经有回归数据，直接使用
				const regression = this.regressionData || this.calculateRegressionLine();
				console.log('regression', regression);
				if (!regression) {
					uni.showToast({
						title: "无法计算回归线，请重试",
						icon: "none"
					});
					return;
				}

				const {
					slope,
					intercept
				} = regression;

				// 如果有v0值，计算1RM
				if (this.v0 != null) {
					// 使用v0计算1RM: y = slope * x + intercept，当x=v0时，y就是1RM
					this.accurateE1rm = (slope * this.v0 + intercept).toFixed(2);
					console.log('计算得到的1RM:', this.accurateE1rm, 'V0:', this.v0);
				} else {
					// 当没有v0时，使用最大成功举起重量作为1RM
					if (this.maxSuccessWeight > 0) {
						// 设置1RM为最大成功举起重量
						this.accurateE1rm = this.maxSuccessWeight.toFixed(2);

						// 通过回归直线反向计算v0
						// 公式：y = slope * x + intercept，求x
						// x = (y - intercept) / slope
						this.v0 = ((this.maxSuccessWeight - intercept) / slope).toFixed(4);

						console.log('使用最大重量作为1RM:', this.accurateE1rm, '反向计算的V0:', this.v0);
					} else {
						uni.showToast({
							title: "没有成功记录，无法计算1RM",
							icon: "none"
						});
						return;
					}
				}

				// 添加线性回归线
				this.addLinearSeries(regression);
			},

			/** 添加线性回归线 */
			addLinearSeries(linear) {
				const {
					slope,
					intercept
				} = linear;

				// 获取当前y轴的最大值
				const max = this.option.yAxis.max || this.getSmw(1);
				const min = this.getSmw(0.2);
				const lineData = [];

				for (let x = min; x <= max; x += min) {
					const y = (x - intercept) / slope;
					lineData.push([y, x]);
				}
				console.log('绘制直线数据lineData', lineData);
				const series = {
					data: lineData,
					smooth: true,
					symbolSize: 8,
					type: "line",
					lineStyle: {
						normal: {
							color: "#6e58aa"
						}
					},
					itemStyle: {
						normal: {
							color: "#6e58aa"
						}
					},
					label: {
						show: false
					}
				};

				if (this.option.series.length == 1) {
					this.option.series.push(series);
				} else {
					this.option.series[1] = series;
				}

				this.$refs.chartRef.setOption(this.option);
			},

			/** 根据百分比计算重量 */
			getSmw(percent) {
				return Math.round(this.limitWeight * percent / 5) * 5;
			}
		},
		mounted() {
			this.initializePage();
			this.deviceData = uni.getStorageSync("deviceData");
			tool.initBluetoothConnectionListener(() => {
				this.deviceData = uni.getStorageSync("deviceData");
			});
			tool.getBlueStatus();
			this.getE1rmZeroRecordApi();
		},
		onUnload() {
			// 页面卸载时停止传感器
			this.stopSensors();
		},
		components: {
			Countdown
		}
	};
</script>

<style lang="less" scoped>
	.container {
		padding: 30rpx;
		box-sizing: border-box;
		height: 100%;
		font-family: PingFangSC-Semibold, PingFang SC;
		color: #333;
		padding-bottom: 50rpx;
		overflow-y: scroll !important;

		.titleTop {
			font-family: "优设标题黑";

			.text {
				font-size: 20px;
				background-image: linear-gradient(to right, #6e58aa, #f17071);
				-webkit-background-clip: text;
				color: transparent;
				margin-bottom: -10px;
				width: fit-content;
			}

			.line {
				width: 70px;
			}
		}

		.stepBox {
			font-family: "优设标题黑";

			.tip {
				display: block;
				font-size: 20px;
				color: #6e58aa;
				width: 100%;
				text-align: center;
				margin: 30px 0;
				margin-top: 40px;
			}

			.btnBox {
				width: 40%;
				border-radius: 15px;
				height: 35px;
				font-size: 24px;
				color: #fff;
				line-height: 35px;
				text-align: center;
				background-color: #6e58aa;
				text-shadow: 2px 4px 6px rgba(0, 0, 0, 0.25);
				position: fixed;
				bottom: 7%;
				left: 50%;
				transform: translate(-50%, 0);
			}

			.btnBox2 {
				width: 40%;
				border-radius: 15px;
				height: 35px;
				font-size: 24px;
				color: #fff;
				line-height: 35px;
				text-align: center;
				background-color: #6e58aa;
				// text-shadow: 2px 4px 6px rgba(0, 0, 0, 0.25);
			}

			.btnBox-row {
				display: flex;
				justify-content: space-between;
				width: 90%;
				position: fixed;
				bottom: 7%;
				left: 50%;
				transform: translate(-50%, 0);
			}

			.btnBox2.success {
				width: 45%;
				background-color: #6e58aa;
			}

			.btnBox2.fail {
				width: 45%;
				background-color: #fff;
				color: #6e58aa;
			}
		}

		.selectAction {
			.actionSelectRow {
				display: grid;
				grid-template-columns: 1fr 1fr;
				gap: 20px;

				.actionItem {
					background-color: rgba(110, 88, 170, 0.12);
					display: flex;
					border-radius: 20rpx;
					padding: 20rpx;
					align-items: center;

					image {
						width: 100rpx;
						height: 100rpx;
						margin-right: 20rpx;
						opacity: 0.6;
					}

					.right {
						.title {
							font-size: 32rpx;
							font-weight: 500;
							margin-bottom: 15rpx;
						}

						.content {
							margin-top: 10rpx;
							font-size: 20rpx;
							font-weight: 400;
							color: rgba(124, 124, 126, 1);
						}
					}
				}
			}
		}

		.inputBoxRow {
			.inputBox {
				display: flex;
				align-items: center;
				margin-top: 73px;
				justify-content: center;

				input {
					width: 120px;
					height: 32px;
					line-height: 18px;
					border-radius: 2px;
					background: #fff;
					padding: 4rpx;
					margin-right: 18rpx;
					box-shadow: 0px 2px 4px rgba(110, 88, 170, 0.2);
					font-size: 18px;
				}
			}
		}

		.testRow {
			.textBox {
				text-align: center;
				font-size: 24px;
				margin-top: 38px;
				color: #6e58aa;
			}

			.E1rm {
				font-size: 60px;
				background: linear-gradient(to right, #6e58aa, #ce96ce);
				background-clip: text;
				-webkit-background-clip: text;
				-webkit-text-fill-color: transparent;
				text-align: center;
			}

			.content {
				color: #6e58aa;
				font-size: 13px;
				border-radius: 4px;
				background: rgba(110, 88, 170, 0.2);
				padding: 10rpx;
				display: flex;
				justify-content: space-between;
				margin-top: 20rpx;

				image {
					width: 50rpx;
					height: 50rpx;
					border-radius: 50%;
				}
			}

			.swiperRow {
				margin-top: 20px;

				.swiperItem {
					.weight {
						font-size: 48px;
						text-align: center;
						position: relative;
						color: #6e58aa;

						.unit {
							display: flex;
							align-items: center;
							justify-content: center;
							position: absolute;
							font-size: 16px;
							right: 12px;
							top: 30px;

							.round {
								width: 30rpx;
								height: 30rpx;
								border-radius: 50%;
								box-shadow: 4px 4px 12px 1px rgba(172, 51, 193, 0.25);
								margin-left: 14rpx;
								margin-right: 46rpx;
							}

							.red {
								background-color: rgba(212, 48, 48, 0.85);
							}

							.yellow {
								background-color: rgba(231, 234, 18, 0.8);
							}

							.green {
								background-color: rgba(118, 214, 62, 0.85);
							}

						}
					}
				}
			}

			.echartBox {
				margin-top: 20rpx;
				width: 100%;
				height: 226px;
				background: #f2f2f3;
				box-shadow: 0px 2px 4px rgba(110, 88, 170, 0.23);
			}
		}
	}

	// 去掉页面滚动条
	::-webkit-scrollbar {
		display: none !important;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
	}

	.weight-input {
		font-size: 48px;
		color: #6e58aa;
		text-align: center;
		width: 100%;
		background: transparent;
		border: none;
		outline: none;
		height: 60px;
		font-family: "优设标题黑";

	}

	/* 微信小程序 */
	input.placeholder {
		color: #6e58aa;
		font-size: 48px;
		font-family: "优设标题黑";
	}

	&::placeholder {
		font-family: "优设标题黑";
		color: #6e58aa;
		font-size: 48px;

	}
</style>
<style lang="less">
	.weight-input {
		font-size: 45px;
		color: #6e58aa;
		text-align: center;
		width: 100%;
		background: transparent;
		border: none;
		outline: none;
		height: 60px;
		font-family: "优设标题黑";

		&::placeholder {
			font-family: "优设标题黑";
			color: #6e58aa;
			font-size: 45px;

		}

	}

	/* 微信小程序 */
	input.placeholder {
		color: #6e58aa;
		font-size: 45px;
		font-family: "优设标题黑";
	}
</style>